#!/usr/bin/env python


# MMDS Server Console v0.1


# Deleting User from MMDS


import os

import sys

import string

import fcntl


# mmds conf directory


try:

    Conf_dir = os.environ["mmdsDIR"]
    

except KeyError:

    Conf_dir = os.getcwd()



Ulist_file = os.path.join(Conf_dir, "users.list")

mmdsdpid = os.path.join(Conf_dir, "mmdsd.pid")



def main():

    try:

        uname = sys.argv[1]

    except:

        sys.stderr.write("usage: mmds-userdel name\n")

        sys.exit()

    else:

        remove_user(uname)

    sys.exit()

    


def remove_user(uname):

    try:

        fp = open(Ulist_file)

    except IOError, e:

        sys.stderr.write("Can't modify users.list: " + e[1] + "\n")

        sys.exit(1)

    else:

        fcntl.flock(fp.fileno(), fcntl.LOCK_SH)

        userlist = fp.readlines()

        fcntl.flock(fp.fileno(), fcntl.LOCK_UN)

        fp.close()

        uindex = {}

        for j in xrange(len(userlist)):

            luname = string.split(userlist[j], ":")

            uindex[luname[0]] = j

        if uindex.has_key(uname):

            userlist.pop(uindex[uname])

            rewrite_list(userlist)

            sys.stdout.write("\nUser " + uname + " succesfully deleted.\n")

        else:

            sys.stderr.write("Can't find user: " + uname + "\n")

            sys.exit(1)

            

def rewrite_list(userlist):

    try:

        fp = open(Ulist_file, 'w')

    except IOError, e:

        sys.stderr.write("Can't write to users.list: " + e[1] + "\n")

        sys.exit(1)

    else:

        fcntl.flock(fp.fileno(), fcntl.LOCK_EX)

        for i in xrange(len(userlist)):

            fp.write(userlist[i])

        fcntl.flock(fp.fileno(), fcntl.LOCK_UN)

        fp.close()

        restart()

            

def restart():

    try:

        pid = open(mmdsdpid).read()

        pid = string.atoi(pid)

    except (IOError, ValueError):

        pass

    else:

        print "\nSending HUP signal to mmdsd."

        try:

            os.kill(pid, 1)

        except OSError, e:

            sys.stderr.write(e[1] + '\n')

    print "\nAll Done."




os.umask(0066)


main()

